<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<html>
  <head>
    <title>Mapa Farmàcies</title>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyDzpJACBJTRWirTRyuAnUkw6LwPhN2pxDk&sensor=false&language=ca"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
//<![CDATA[

// Get the URL variables (if given)
var arrURL=window.location.search.substr(1).split("&");
for (i=0;i<arrURL.length;i++) {
	arrURL[i]=arrURL[i].split("=");
}
var qStr=[];
for (i=0;i<arrURL.length;i++) {
	qStr[arrURL[i][0]]=arrURL[i][1];
}
if (qStr['bzoom']!=null) {
	var	bzoom = parseInt(qStr['bzoom']);
} else {
	var	bzoom = 16;
}

// Google map vars
var map;
var bounds;
var f_arr = [];
var fidArr = [];
var link_arr = [];
var sidebarmarkers = [];
var stylesdb = {};
var styleurldb = {};
var outputhtml ='';
var j = 0;
var old_f = -1;

var maptiler = new google.maps.ImageMapType({ 
	getTileUrl: function(a, b) { 
		var tile = "maptiles/zoom"+b+"/"+a.x+"_"+a.y+"_"+b+".png";
		switch (b) {
			case 5:
			if ((a.x==15||a.x==16) && a.y==12) {
				return tile;
			}
			break;
			case 6:
			if ((a.x==31||a.x==32) && a.y==24) {
				return tile;
			}
			break;
			case 7:
			if ((a.x==63||a.x==64) && a.y==48) {
				return tile;
			}
			break;
			case 8:
			if ((a.x==127||a.x==128) && a.y==97) {
				return tile;
			}
			break;
			case 9:
			if ((a.x==255||a.x==256) && a.y==194) {
				return tile;
			}
			break;
			case 10:
			if (a.x==511 && a.y==388) {
				return tile;
			}
			break;
			case 11:
			if (a.x==1022 && a.y==777) {
				return tile;
			}
			break;
			case 12:
			if (a.x==2044 && a.y==1554) {
				return tile;
			}
			break;
			case 13:
			if (a.x==4089 && a.y==3109) {
				return tile;
			}
			break;
			case 14:
			if (a.x==8179 && a.y==6218) {
				return tile;
			}
			break;
			case 15:
			if ((a.x==16358||a.x==16359) && a.y==12437) {
				return tile;
			}
			break;
			case 16:
			if (a.x>=32717 && a.x<=32719 && a.y>=24874 && a.y<=24875) {
				return tile;
			}
			break;
			case 17:
			if (((a.x>=65436 && a.x<=65438 && a.y>=49748 && a.y<=49751) || (a.x==65435 && a.y==49750)|| (a.x==65439 && a.y==49750))) {
				return tile;
			}
		}
	}, 
	tileSize: new google.maps.Size(256, 256), 
}); 

function initialize() {
	$.ajax({
		async: false,
		type: 'GET',
		dataType: 'text',
		url: 'https://docs.google.com/spreadsheet/pub?key=0Al51BM90Pqc8dGZONGd0bllENkl5bGd5LWtMMy1oeGc&single=true&gid=6&range=B1%3AB4&output=csv',
		success: function(data) {
			fidArr = data.split(/\n/);
			//$.each(fidArr, function (key,val) { console.log(val); });
		}
	});

	map = new google.maps.Map(document.getElementById("mapbox"), {
	zoom: 16,
	maxZoom: 17,
	center: new google.maps.LatLng(39.72789258893543, -0.2694869041442871),
	mapTypeId: google.maps.MapTypeId.ROADMAP
	});

	map.overlayMapTypes.insertAt(0, maptiler);
	
	$.ajax({
		async: false,
		type: 'GET',
		url: "farmacies.kml",
		success: function(data) {
		
  		var pfolders = data.documentElement.getElementsByTagName("Folder");
  		
  		for (var j = 0; j < pfolders.length; j++) {
  			
  			// for folder containing placemarks -> checkboxes
  			if (pfolders[j].getElementsByTagName("name")[0].firstChild.nodeValue == "farmacies") {
  				var placemarks = pfolders[j].getElementsByTagName("Placemark");
  				for (var i = 0; i < placemarks.length; i++) {
  					var coordinates = placemarks[i].getElementsByTagName("coordinates")[0].childNodes[0].nodeValue.split(",");
						var f_index = placemarks[i].getElementsByTagName("fid")[0] ? parseInt(placemarks[i].getElementsByTagName("fid")[0].childNodes[0].nodeValue) : '';						
						var f_obj = placemarks[i].getElementsByTagName("styleUrl")[0].childNodes[0].nodeValue.substring(1);
  					stylesdb[f_obj] = {
  						place : placemarks[i].getElementsByTagName("name")[0].childNodes[0].nodeValue,
  						lat :	parseFloat(coordinates[1]),
  						lon : parseFloat(coordinates[0]),
  						desc : placemarks[i].getElementsByTagName("description")[0] ? placemarks[i].getElementsByTagName("description")[0].childNodes[0].nodeValue : '',
  						fid: f_index
  					}
  					//console.log("f_index is "+f_index);
						// Assign html to each active pharmacy
  					switch (f_index) {
  						case parseInt(fidArr[0]):
  							//00to09
  							var html1 = '<table width=100%><tr><td class="phbox"><b>Fins les 9 del matí:</b><br /><a href="javascript:zoomBoundsAndView('+f_index+')"><img src="mapicons/icon46_mod.png" border="0" /><br />'+stylesdb[f_obj].place+'</a><br />'+stylesdb[f_obj].desc+'</td>';
  							break;
  						case parseInt(fidArr[1]):
  							//09to21
  							var html2 = '<td class="phbox"><b>De 9 de hui a 9 de demà:</b><br /><a href="javascript:zoomBoundsAndView('+f_index+')"><img src="mapicons/icon46_mod.png" border="0" /><br />'+stylesdb[f_obj].place+'</a><br />'+stylesdb[f_obj].desc+'</td></tr>';
  							break;
  						case parseInt(fidArr[2]):
  							//09to22
  							var html3 = '<td class="phbox"><b>De 9 a 21 hores:</b><br /><a href="javascript:zoomBoundsAndView('+f_index+')"><img src="mapicons/icon46_mod.png" border="0" /><br />'+stylesdb[f_obj].place+'</a><br />'+stylesdb[f_obj].desc+'</td>';
  							break;
  						case parseInt(fidArr[3]):
  							//09to09
  							var html4 = '<td class="phbox"><b>De 9 a 22 hores:</b><br /><a href="javascript:zoomBoundsAndView('+f_index+')"><img src="mapicons/icon46_mod.png" border="0" /><br />'+stylesdb[f_obj].place+'</a><br />'+stylesdb[f_obj].desc+'</td></tr></table>';
  					}
					}
				}
  		}

  		// <Style id="identifier"><href> ::: contains the URL for each icon
			var styleidarr = data.documentElement.getElementsByTagName("Style");
  		for (var i = 0; i < styleidarr.length; i++) {
  			styleurldb[styleidarr[i].getAttribute('id')] = {iconhref : styleidarr[i].getElementsByTagName("href")[0] ? styleidarr[i].getElementsByTagName("href")[0].childNodes[0].nodeValue : ''};
  		}
  		
			// <StyleMap id="identifier"><styleUrl> ::: contains the style id of each marker
  		var stylemapidarr = data.documentElement.getElementsByTagName("StyleMap");
  		for (var i = 0; i < stylemapidarr.length; i++) {
  			var stylemapid = stylemapidarr[i].getAttribute('id');
  			if (stylesdb[stylemapid]!=null) {
  				stylesdb[stylemapid].styleurl = stylemapidarr[i].getElementsByTagName("styleUrl")[0] ? stylemapidarr[i].getElementsByTagName("styleUrl")[0].childNodes[0].nodeValue.substring(1) : '';
  				stylesdb[stylemapid].iconhref = styleurldb[stylesdb[stylemapid].styleurl].iconhref;
  				createMarker(stylesdb[stylemapid].lat, stylesdb[stylemapid].lon, stylesdb[stylemapid].place, stylesdb[stylemapid].desc, stylesdb[stylemapid].iconhref, stylesdb[stylemapid].fid);
  			}	
  		}
  		document.getElementById("pharms").innerHTML = ( typeof(html1)=="undefined" ? '<table width=100%><tr><td style="padding:35px;" align="center">Els dilluns no n\'hi ha farm&agrave;cia de gu&agrave;rdia fins les 9 del mat&iacute;.</td>' : html1 )+html2+html3+( typeof(html4)=="undefined" ? '<td style="padding:35px;" align="center">Els diumenges no n\'hi ha farm&agrave;cia de gu&agrave;rdia des de les 22 hores fins les 9 del mat&iacute; del dilluns.</td></tr></table>' : html4);
}
		});

		function createMarker(lat, lon, locname, desc, iconhref, fid) {
			var marker = new google.maps.Marker({
				icon: new google.maps.MarkerImage(iconhref),
				position: new google.maps.LatLng(parseFloat(lat),parseFloat(lon))
			});
			var infoWindow = new google.maps.InfoWindow();
			google.maps.event.addListener(marker, "click", function() {
				infoWindow.setContent('<b>'+locname+'</b><br />'+desc);
				infoWindow.open(map,this);
			});
			//var icon = new GIcon(baseIcon, iconhref, null, iconhref.slice(0,-4)+'s.png');
			google.maps.event.addListener(marker, "mouseover", function() {
				map.panTo(marker.getPosition());
			});
			sidebarmarkers[fid] = marker;
			//j++;
			//return marker;
		}
    
}		

	function zoomBoundsAndView(f) {
		if (old_f!=-1){
			sidebarmarkers[old_f].setMap(null);
		}
		bounds = new google.maps.LatLngBounds();
    bounds.extend(new google.maps.LatLng(39.72789258893543, -0.2694869041442871));
		bounds.extend((sidebarmarkers[f].getPosition()));
		map.fitBounds(bounds);
		//map.setZoom(map.fitBounds(bounds));
		//map.panTo(bounds.getCenter());
		sidebarmarkers[f].setMap(map);
		google.maps.event.trigger(sidebarmarkers[f], "click");
		old_f = f;
	}
	
	function showhideAllMarkers(s) {
		a = document.getElementById('veureamagar').innerHTML;
		if (a=='Veure') {
			document.getElementById('veureamagar').innerHTML = 'Amagar';
			for (i in sidebarmarkers) {
				if (i!=s) { sidebarmarkers[i].setMap(map);
				}
			}
		} else if (a=='Amagar') {
			document.getElementById('veureamagar').innerHTML = 'Veure';
			for (i in  sidebarmarkers) {
				if (i!=s) {
				sidebarmarkers[i].setMap(null);
				}
			}
		}
	}
	
	function centerMarker(m) {
		map.panTo(sidebarmarkers[m].getPosition());
		google.maps.event.trigger(sidebarmarkers[m], "click");
	}
//]]>
</script>
<style type="text/css">
	<!--
body {
	font-family: Arial, Helvetica, sans-serif;
	font-size: small;
}
a {
	text-decoration: none;
}
a:link {
	color: #360;
}
a:visited {
	color: #090;
}
a:hover {
	color: #000;
}
a:active {
	color: #099;
}

.phbox {
	padding: 10px 30px;
	width: 50%;
	border: 4px solid #DEB;
}
.phbox a {
	font-weight: bold;
}

#controls {
	margin-top: 2px;
}

#controls a {
	line-height: 30px;
	background-color: #DDD;
	border: 2px outset #360;
	padding: 5px;
}

#controls a:hover {
	background-color: #DEB;
	border: 2px inset #360;
}

-->
</style>
  </head>
  <body onload="initialize()">
  		<h3>Farm&agrave;cies de gu&agrave;rdia hui <?php echo strftime("%A %d de %B"); ?></h3>
  		<b>Clica el nom de la farm&agrave;cia per a veure-la en el mapa de baix:</b>
  	<div id="pharms">
  	</div>
  	<br />
		<script type="text/javascript">
  	document.write('<div id="mapbox" style="width: 600px; height: 500px; clear: both"></div>');
  	</script>
  	<div style="clear: both">
			<div id="controls">
				<a href='javascript:map.panTo(new google.maps.LatLng(39.72789258893543, -0.2694869041442871))'>Centrar mapa en Benifair&oacute; de les Valls</a>&nbsp;
				<a href='javascript:showhideAllMarkers(3);'><span style='display: inline' id="veureamagar">Veure</span> altres farm&agrave;cies</a><br />
			</div>
		</div>
  </body>
</html>